from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect
import logging
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

logger = logging.getLogger(__name__)

@csrf_exempt
class AuthMiddleware(MiddlewareMixin):
    @csrf_exempt
    def process_request(self, request):
        # 要绕过验证的IP地址段
        bypass_ip_prefix = '192.168.123'

        # 获取请求的IP地址
        ip = request.META.get('HTTP_X_FORWARDED_FOR')
        if ip:
            ip = ip.split(',')[0].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')

        # 打印调试信息
        print(f"Request IP: {ip}")

        # 如果请求来自特定IP地址段，则绕过验证
        if ip.startswith(bypass_ip_prefix):
            logger.debug(f"Bypassing authentication for IP: {ip}")
            return

        # 检查不需要验证的路径
        if request.path_info in ["/xybl/Psychologist_add/", "/xybl/Police_add", "/xybl/Psychologist_or_Police_login/"]:
            return

        # 打印Cookie和Session信息
        print(request.COOKIES)
        print(request.session.get('user_id'))

        # 检查用户是否已登录
        info_dict = request.session.get("user_id")
        if info_dict is not None:
            logger.debug(f"User logged in: {info_dict}")
            return

        # 如果用户未登录，返回403响应
        logger.warning("User not logged in")
        return JsonResponse({'status': False, 'message': '用户未登录'}, status=403)
